通过 ALSA 显示音频设备的声道

1// apt install libasound2-dev
2// LDFLAGS := -lasound
3#include <stdio.h>
4#include <stdlib.h>
5#include <alsa/asoundlib.h>
6
7int main(int argc, char* argv[])
8{
9    if(argc != 2)
10    {
11        fprintf(stderr, "Usage: %s <device>\n", argv[0]);
12        fprintf(stderr, "       %s hw:0,0\n", argv[0]);
13        return EXIT_FAILURE;
14    }
15
16    snd_pcm_t* pcm = NULL;
17    if(snd_pcm_open(&pcm, argv[1], SND_PCM_STREAM_PLAYBACK, 0) < 0)
18    {
19        fprintf(stderr, "snd_pcm_open failed\n");
20        return EXIT_FAILURE;
21    }
22
23    snd_pcm_chmap_query_t** chmaps = snd_pcm_query_chmaps(pcm);
24    if(chmaps == NULL)
25    {
26        fprintf(stderr, "snd_pcm_query_chmaps failed\n");
27        return EXIT_FAILURE;
28    }
29
30    for(int i = 0; chmaps[i] != NULL; i++)
31    {
32        snd_pcm_chmap_query_t* mapping = chmaps[i];
33        printf("Mapping-%d\n", i);
34        for(int ch = 0; ch < mapping->map.channels; ch++)
35        {
36            printf("\tchannel-%d %s\n", ch, snd_pcm_chmap_long_name(mapping->map.pos[ch]));
37        }
38    }
39
40    snd_pcm_free_chmaps(chmaps);
41
42    return EXIT_SUCCESS;
43}